package com.leo.tagfilter.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class MyConsumerTag1 {
    public static void main(String[] args) throws MQClientException {

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_grp_06_03");

        consumer.setNamesrvAddr("localhost:9876");
        // 设置负载均衡算法
        consumer.setAllocateMessageQueueStrategy(new AllocateMessageQueueAveragely());

        // 消费的模式：集群
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 消费的模式：广播
        //consumer.setMessageModel(MessageModel.BROADCASTING);

        //consumer.subscribe("tp_demo_06", "*");
        //consumer.subscribe("tp_demo_06", "tag-1");
        //consumer.subscribe("tp_demo_06", "tag-1||tag-0");
        consumer.subscribe("tp_demo_06", MessageSelector.byTag("tag-1||tag-2"));

        // 设置消息重试次数, 16个级别（广播模式无效, 有序消息会不断重试，间隔1秒，会阻塞后续消息的消费）
        consumer.setMaxReconsumeTimes(5);
        // 设置消息批处理的一个批次中消息的最大个数
        consumer.setConsumeMessageBatchMaxSize(1);


        /** push模式 */
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                final MessageQueue messageQueue = context.getMessageQueue();
                final String brokerName = messageQueue.getBrokerName();
                final String topic = messageQueue.getTopic();
                final int queueId = messageQueue.getQueueId();

                System.out.println(brokerName + "\t" + topic + "\t" + queueId);

                for (MessageExt msg : msgs) {
                    System.out.println(msg);
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                //return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        // 初始化并启动消费者
        consumer.start();

    }
}
